package com.hexun.dubbo.utils;

import com.alibaba.dubbo.rpc.RpcContext;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Rpc Context Utils
 */
public class RpcContextUtils {

    /**
     * get http servlet request
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getHttpServletRequest() {
        HttpServletRequest request = RpcContext.getContext().getRequest(HttpServletRequest.class);
        return request;
    }

    /**
     * get http servlet response
     *
     * @return HttpServletResponse
     */
    public static HttpServletResponse getHttpServletResponse() {
        HttpServletResponse response = RpcContext.getContext().getResponse(HttpServletResponse.class);
        return response;
    }

    /**
     * 获取rpc请求头
     *
     * @return
     */
    public static String getRequestHost() {
        HttpServletRequest httpServletRequest = getHttpServletRequest();
        if (httpServletRequest != null) {
            return httpServletRequest.getServerName();
        }
        return null;
    }

    /**
     * 获取 request multipart form map
     *
     * @return
     */
    public static Map<String, FileItem> getMultipartFormMap() {
        HttpServletRequest request = getHttpServletRequest();
        if (request == null) {
            return null;
        }
        if (isMultipartForm(request)) {
            try {
                Map<String, FileItem> map = new HashMap<String, FileItem>();
                List<FileItem> items = SERVLET_FILE_UPLOAD.parseRequest(request);
                for (FileItem item : items) {
                    map.put(item.getFieldName(), item);
                }
                return map;
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 是否 multipart form
     *
     * @return
     */
    public static boolean isMultipartForm(HttpServletRequest request) {
        return request != null && ServletFileUpload.isMultipartContent(request);
    }

    /**
     * default DiskFileItemFactory
     */
    final static ServletFileUpload SERVLET_FILE_UPLOAD = new ServletFileUpload(new DiskFileItemFactory());
}
